/**餐桌包房管理
 * Created by huotaol on 2017/9/30.
 */
import {Button, Form, Input, Modal, Popconfirm, Select, Table} from "antd";
import React from "react";
import {connect} from "react-redux";
import {fetchData, receiveData} from "@/action";
import request, {get} from "@/axios/tools";
import {bindActionCreators} from "redux";
const FormItem = Form.Item;
const Option = Select.Option;

const tableTypes = [
    {name: "餐桌", value: 'DINING_TABLE'},
    {name: '包房', value: 'PRIVATE_ROOM'},
    {name: "卡座", value: 'CASSETTE'}
];

class TableOrRoomList extends React.Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            data: [],
            showAdd: false,
            loading: false,
            editType: 'add',
            editId: '',
        };
    }

    componentDidMount() {
        this._requestData();
    }


    _requestData = (type) => {
        this.type = type;
        const {auth: auth = {data: {}}} = this.props;
        if (auth.data.restaurant) {
            get('/restaurant/listTableOrRoom', {
                restaurantID: auth.data.restaurant,
                type: type || ''
            }).then(data => {
                data = data.map(item => {
                    return {...item, key: item.id};
                });
                this.setState({data});
            });
        }
    };

    handleCancel = () => {
        this.setState({showAdd: false});
    };

    handleCreate = () => {
        const form = this.form;
        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            const {auth: auth = {data: {}}} = this.props;
            const {editId, editType} = this.state;
            if (auth.data.restaurant) {
                this.setState({loading: true});
                values = {...values, restaurantID: auth.data.restaurant};
                if (editType === 'save' && editId !== '') {
                    values.id = editId;
                }
                console.log('Received values of form: ', values);
                request({url: '/restaurant/tableOrRoom', method: 'post', params: values}).then(data => {
                    form.resetFields();
                    this.setState({showAdd: false, loading: false});
                    this._requestData(this.type);
                }).catch(e => {
                    this.setState({loading: false});
                });
            }
        });
    };
    saveFormRef = (form) => {
        this.form = form;
    };

    handleEdit = (record) => {
        this.form.setFieldsValue({
            orderNum: record.orderNum,
            type: record.type
        })
        this.setState({showAdd: true, editType: 'save', editId: record.id});
        // console.log(record)
    }

    handleDelete = (record) => {
        request({url: '/restaurant/tableOrRoom/' + record.id, method: 'delete'}).then((res) => {
            console.log(res);
            this._requestData(this.type);
        }, (err) => {
            console.log(err);
        })
    };

    render() {
        const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;
        const columns = [{
            title: 'ID',
            dataIndex: 'id'
        }, {
            title: '编号',
            dataIndex: 'orderNum'
        }, {
            title: '类型',
            dataIndex: 'type',
            render: text => {
                // tableType : {name: '...', value:'...'}
                return tableTypes.filter((tableType) => {
                    return tableType.value === text;
                })[0].name;
            }
        }, {
            title: '类型',
            width: 200,
            render: (text, record, index) => (
                <span>
                  <Button className="plus-btn" type="dashed" icon="edit" onClick={() => this.handleEdit(record)}>
                    编辑
                  </Button>
                  <Popconfirm title="确定删除?" onConfirm={() => this.handleDelete(record)}>
                      <Button type="dashed">删除</Button>
                  </Popconfirm>
                </span>
            )
        }];
        return (
            <div className="content-container">
                <Select placeholder={'选择类型'} style={{width: 120}} allowClear onChange={v => {
                    this._requestData(v);
                }}>
                    {tableTypes.map((item, index) =>
                        <Option value={item.value}
                                key={item.value}> {item.name}</Option>)}
                </Select>
                <Button style={{margin: 20}} onClick={e => {
                    this.form.resetFields()
                    this.setState({showAdd: true, editType: 'add'});
                }}>添加</Button>
                <div className="space-bar"></div>
                <Table columns={columns} dataSource={this.state.data}/>
                <CollectionCreateForm
                    ref={this.saveFormRef}
                    visible={this.state.showAdd}
                    onCancel={this.handleCancel}
                    onCreate={this.handleCreate}
                    loading={this.state.loading}
                    editType={this.state.editType}
                />
            </div>
        );
    }
}

const CollectionCreateForm = Form.create()(
    (props) => {
        const {visible, onCancel, onCreate, form, loading, editType} = props;
        const {getFieldDecorator} = form;
        return (
            <Modal
                visible={visible}
                title="创建餐桌或包房"
                okText={editType === 'add' ? '创建' : '保存'}
                onCancel={onCancel}
                onOk={onCreate}
                confirmLoading={loading}
            >
                <Form>
                    <FormItem label="编号">
                        {getFieldDecorator('orderNum', {
                            rules: [{required: true, message: '请输入编号'}],
                        })(
                            <Input />
                        )}
                    </FormItem>
                    <FormItem label="类型">
                        {getFieldDecorator('type', {
                            rules: [{required: true, message: '请选择类型'}],
                        })(
                            <Select placeholder={'选择类型'} style={{width: 120}} allowClear
                            >
                                {tableTypes.map((item, index) =>
                                    <Option value={item.value}
                                            key={item.value}> {item.name}</Option>)}
                            </Select>
                        )}
                    </FormItem>
                </Form>
            </Modal>
        );
    }
);


const mapStateToPorps = state => {
    const {auth} = state.httpData;
    return {auth};
};
const mapDispatchToProps = dispatch => ({
    fetchData: bindActionCreators(fetchData, dispatch),
    receiveData: bindActionCreators(receiveData, dispatch)
});


export default connect(mapStateToPorps, mapDispatchToProps)(Form.create()(TableOrRoomList));